﻿#ifndef __SS_LE_SERVER_H__
#define __SS_LE_SERVER_H__
#include "ssBaseDefine.h"
#include "tools/ssIDAlloter.h"
#include <event2/event.h>
#include <event2/listener.h>
#include <event2/bufferevent.h>
#include <event2/buffer.h>
#include <event2/util.h>
#include <event2/thread.h>
#include <string>
#include "ssLeSession.h"

namespace StarSeeker
{

class ssLeServer
{
public:
	ssLeServer();
	~ssLeServer();

	//启动监听
	bool CreateListen(const char* ip, const u16 port);
	//启动消息处理
	void StartDispatch();
	//停止服务
	void StopServer();
	//连接网络
	bool CreateConnect(const char* ip, const u16 port);
	//重新连接
	bool Reconnect();
	//设置读写缓冲区
	void SetRWBufferSize(u32 len);
	//返回处理粘包方式
	u8 GetParsePackageMode() { return m_parsePackageMode; }
protected:
	virtual void OnNewConnection(ssLeSession *session);
	virtual void AfterSend(ssLeSession *session);
	virtual void OnReceive(ssLeSession *session, char *data, u32 len);
	virtual void OnError(ssLeSession *session, short error);
private:
	static void conn_writecb(bufferevent *bev, void *user_data);
	static void conn_readcb(bufferevent *bev, void *user_data);
	static void conn_errorcb(bufferevent *bev, short error, void *ctx);
	static void conn_signalcb(evbuffer* bev, const evbuffer_cb_info* info, void* ctx);
	static void accept_cb(evconnlistener *listener, evutil_socket_t fd, sockaddr *sa, int socklen, void *user_data);

protected:
	event_base*			m_base;
	evconnlistener*		m_listener;//服务端监听器
	ssCumulationID<u32>	m_idAlloter;
	bool				m_isClient;
	u32					m_rwSize;//读写缓冲区大小
	std::string			m_connectIP;
	u16					m_connectPort;
	u8					m_parsePackageMode;
};

}
#endif
